package air2.totc.messaging;

import java.util.List;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsMessage;
import android.widget.*;

public class smsIntercepteur extends BroadcastReceiver {
	 private final String   ACTION_RECEIVE_SMS  = "android.provider.Telephony.SMS_RECEIVED";
	 GestionSMS gestionnaireSMS;
	 @Override
	 public void onReceive(Context context, Intent intent)
	 {
		 Toast.makeText(context, "sms reçu", Toast.LENGTH_LONG).show();
		 if (intent.getAction().equals(ACTION_RECEIVE_SMS))
		 {
			 Bundle bundle = intent.getExtras();
			 if (bundle != null)
			 {
				 Object[] pdus = (Object[]) bundle.get("pdus");
				 SmsMessage[] messages = new SmsMessage[pdus.length];
				 for (int i = 0; i < pdus.length; i++)  {  messages[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);  }  if (messages.length > -1)
				 {
					 //TODO - mettre un traitement sur la reception (annuler le broadcast si c'est pour cryptoSMS
				     Toast.makeText(context,"sms reçu 1",Toast.LENGTH_LONG).show();
					 
					 String messageBody = messages[0].getMessageBody();
					 String phoneNumber = messages[0].getDisplayOriginatingAddress();
					 String[] temp;
					 String  phone="0";
					 gestionnaireSMS = new GestionSMS(context);
					 gestionnaireSMS.open();
					 try{
						 temp = messageBody.split("<>");
							if(phoneNumber.contains("+33")){
								phone = phoneNumber.replace("+33", "0");
							}
							else{
								phone = phoneNumber.toString();
							}
						 if(temp.length>1){
							 Message test=gestionnaireSMS.insertSMS(temp[1], Long.parseLong(phone),Integer.parseInt(temp[0]) ,0);
							 Toast.makeText(context,"ok !!", Toast.LENGTH_LONG).show();
							 //this.abortBroadcast();
						 }
					 }
					 catch(Exception e){
						 Toast.makeText(context, "erreur !!", Toast.LENGTH_LONG).show();
					 }
					 gestionnaireSMS.close();
				 }
			 }
		 }
	 
	 }
}
